//
//  KQMessageAvatarView.swift
//  JChat
//
//  Created by JIGUANG on 10/04/2017.
//  Copyright © 2017 HXHG. All rights reserved.
//

import UIKit
import KQChatSDK

open class KQMessageAvatarView: UIImageView, KQMessageContentViewType {
    
    weak var delegate: KQMessageDelegate?
    
    public override init(image: UIImage?) {
        super.init(image: image)
        _commonInit()
    }
    public override init(image: UIImage?, highlightedImage: UIImage?) {
        super.init(image: image, highlightedImage: highlightedImage)
        _commonInit()
    }
    public override init(frame: CGRect) {
        super.init(frame: frame)
        _commonInit()
    }
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _commonInit()
    }
    
    open func apply(_ message: KQMessageType) {
        self.message = message
        
        if message.senderAvator != nil {
            image = message.senderAvator
            return
        }
//        message.sender?.thumbAvatarData({ [weak self] (data, id, error) in
//            guard let self = self else {
//                return
//            }
//            if let data = data {
//                self.image = UIImage(data: data)
//            } else {
//                self.image = self.userDefaultIcon(user: message.sender)
//            }
//        })
    }
    
    private var message: KQMessageType!
    private func userDefaultIcon(user: WFCCUserInfo?) -> UIImage {
        if user?.name == "0000" {
            // 机器人
            return UIImage.init(named: "kq_chat_robot_header.png")!
        }
//        if user?.gender == .unknown || user?.gender == .male {
//            return UIImage.init(named: "kq_chat_header_man.png")!
//        }
        return UIImage.init(named: "kq_chat_header_woman.png")!
    }
    
    private func _commonInit() {
        self.image = userDefaultIcon(user: nil)
        isUserInteractionEnabled = true
        KQChatUtils.shared().addCorner(on: self, rect: CGRect(x: 0, y: 0, width: 40, height: 40), roundingCorners: UIRectCorner.allCorners, cornerRadius: 3)

        let tapGR = UITapGestureRecognizer(target: self, action: #selector(_tapHandler))
        self.addGestureRecognizer(tapGR)

        let longTapGesture = UILongPressGestureRecognizer(target: self, action: #selector(_longTap(_:)))
        longTapGesture.minimumPressDuration = 0.4
        addGestureRecognizer(longTapGesture)
    }
    
    @objc func _tapHandler(sender:UITapGestureRecognizer) {
        delegate?.tapAvatarView?(message: message)
    }

    @objc func _longTap(_ gestureRecognizer: UILongPressGestureRecognizer)  {
        if gestureRecognizer.state == .began {
            delegate?.longTapAvatarView?(message: message)
        }
    }

}
